package io.github.lee.app.unsplash.ui.main.home

import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.app.unsplash.databinding.FragmentHomeBinding
import io.github.lee.app.unsplash.databinding.LayoutDefaultLoadingBinding
import io.github.lee.app.unsplash.ui.main.home.page.TopicPhotoListFragment
import io.github.lee.core.ui.BaseFragment


@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeVM>() {

    private var mediator: TabLayoutMediator? = null

    companion object{
        fun newInstance(): HomeFragment = HomeFragment()

    }

    //===Desc:======================================================================================
    override fun onCreateViewModel(): HomeVM =
        viewModels<HomeVM>().value

    override fun onCreateLoading(): ViewDataBinding =
        LayoutDefaultLoadingBinding.inflate(layoutInflater)


    override fun onCreateSuccess(): FragmentHomeBinding =
        FragmentHomeBinding.inflate(layoutInflater)

    override fun onDestroyView() {
        super.onDestroyView()
        mediator?.detach()
    }
    //===Desc:======================================================================================

    override fun onObserved() {
        super.onObserved()
        vm?.apply {
            topicList.observe(viewLifecycleOwner) { topics ->
                vb?.apply {
                    vpContent.offscreenPageLimit = topics.size
                    vpContent.adapter = object : FragmentStateAdapter(this@HomeFragment) {
                        override fun getItemCount(): Int = topics.size

                        override fun createFragment(position: Int): Fragment =
                            TopicPhotoListFragment.newInstance(topics[position])
                    }

                    val strategy =
                        TabLayoutMediator.TabConfigurationStrategy { tab, position ->
                            tab.text = topics[position].title
                        }
                    mediator = TabLayoutMediator(tab, vpContent, strategy)
                    mediator?.attach()
                    showSuccess()
                }
            }
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        showLoading()
        vm?.topicList()
    }

}